﻿using System;
using System.Reflection;

namespace Epon.EponEl5600.ViewModel
{
    /// <summary>
    ///     参数显示模块抽象基类
    /// </summary>
    /// <remarks>
    ///     
    /// </remarks>
    public abstract class BaseViewModel<TModel> : NotifyPropertyChanged where TModel : class
    {
        protected TModel Value { get; set; }

        /// <summary>
        ///     设置属性值
        /// </summary>
        /// <param name="propertyName" type="string">
        ///     <para>
        ///      属性名称   
        ///     </para>
        /// </param>
        /// <param name="value" type="object">
        ///     <para>
        ///      属性值   
        ///     </para>
        /// </param>
        public virtual void SetPropertyValue(string propertyName, object value)
        {
            try
            {
                PropertyInfo propertyInfo = typeof(TModel).GetProperty(propertyName);
                propertyInfo.SetValue(Value, value, null);
                OnPropertyChanged(propertyName);
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }

        /// <summary>
        ///     需要处理的参数设置
        /// </summary>
        /// <param name="sign" type="string">
        ///     <para>
        ///         
        ///     </para>
        /// </param>
        /// <param name="splitchar" type="char[]">
        ///     <para>
        ///         
        ///     </para>
        /// </param>
        /// <param name="value" type="object">
        ///     <para>
        ///         
        ///     </para>
        /// </param>
        public void SetPropertyValue(string sign, char[] splitchar, object value)
        {
            string propertyName;
            GetPropertyName(sign, splitchar, out propertyName);
            if (!string.IsNullOrEmpty(propertyName))
                SetPropertyValue(propertyName, value);
        }


        /// <summary>
        ///     传入“PropertyName”需要处理时调用函数，默认取分割后数组的“第一项“.
        ///     如果不符合此情况，请重写此函数
        /// </summary>
        /// <param name="sign" type="string">
        ///     <para>
        ///         PropertyName
        ///     </para>
        /// </param>
        /// <param name="splitchar" type="char[]">
        ///     <para>
        ///         分割标识
        ///     </para>
        /// </param>
        /// <param name="propertyName" type="string">
        ///     <para>
        ///         返回参数名
        ///     </para>
        /// </param>
        protected virtual void GetPropertyName(string sign, char[] splitchar, out string propertyName)
        {
            string[] strs = sign.Split(splitchar);
            propertyName = strs.Length <= 0 ? "" : strs[0];
        }
    }
}
